package com.etoak.controller;

import cn.hutool.core.codec.Base64Encoder;
import cn.hutool.core.util.IdUtil;
import com.etoak.common.core.vo.ResultVO;
import com.etoak.config.KaptchaConfig;
import com.etoak.dto.LoginDTO;
import com.etoak.service.UserService;
import com.etoak.vo.CodeVO;
import com.etoak.vo.TokenVO;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

import static com.etoak.common.constant.CommonConstant.REDIS_KEY_CODE_PREFIX;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    UserService userService;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    KaptchaConfig kaptchaConfig;

    @GetMapping("/code")
    public ResultVO<CodeVO> getCode() {

        DefaultKaptcha kaptcha = kaptchaConfig.getDefaultKaptcha();
        String codeText = kaptcha.createText();
        String uuid = IdUtil.simpleUUID();
        String key = REDIS_KEY_CODE_PREFIX + uuid;

        stringRedisTemplate.opsForValue().set(key, codeText, 3, TimeUnit.MINUTES);

        BufferedImage image = kaptcha.createImage(codeText);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        try {
            ImageIO.write(image, "png", outputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }

        String base64 = Base64Encoder.encode(outputStream.toByteArray());
        String text = "data:image/png;base64," + base64;

        CodeVO vo = new CodeVO(uuid, text);

        return ResultVO.success(vo);
    }

    /**
     * 用户登录
     */
    @PostMapping("/login")
    public ResultVO<TokenVO> login(@Validated LoginDTO loginDTO){
        TokenVO tokenVO = userService.login(loginDTO);
        return ResultVO.success(tokenVO);
    }










}
